package com.foreveross.chameleon.mdm;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Looper;
import com.foreveross.chameleon.base.BslApplication;
import com.foreveross.chameleon.utils.AppLog;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author zhouzhineng
 * @date 2014-10-21
 * @description 应用安装卸载的管理器
 */
//**
//*
//* {
//*      "type": "mdm",
//*      "content": {
//*      "install_app":
//*      [
//*          “http://www.a.b/c1.apk”,
//*          “http://www.a.b/c2.apk”
//*      ]
//*      }
//*  }
//*/
public class InstallMgr {

    public final static String TAG = "InstallMgar";
    public final static String DownloadPath = "/sdcard/chameleon_download";
    private static InstallMgr mInstance;
    private Context mContext;

    public static InstallMgr getInstance() {
        if (mInstance == null) {
            Application app = BslApplication.getApplication();
            mInstance = new InstallMgr(app);
        }

        return mInstance;
    }

    private InstallMgr(Context context) {
        mContext = context;
    }

    public void downloadFileByUrl(String msg) {
        AppLog.d("the Msg Of InstallMgr downloadFileByUrl ===>" + msg);
        try {
            final JSONArray items = new JSONArray(msg);
            for (int i = 0; i < items.length(); i++) {
                final String url = items.getString(i);
                AppLog.d("The download apk url ====> " + url);
                downAndInstallInThread(url);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void downAndInstallInThread(final String url) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    File apkFile = downFileByUrl(url);
                    install(apkFile);
                }
            }).start();
        } else {
            File apkFile = downFileByUrl(url);
            install(apkFile);
        }
    }

    private void install(File apk) {
        if (apk == null) {
            AppLog.e("null apk file, not install");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    private File downFileByUrl(String apkurl) {
        try {
            URL url = new URL(apkurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            if (conn.getResponseCode() != 200) {
                AppLog.e("download fail: url=" + apkurl);
                return null;
            }
            String type = conn.getHeaderField("Content-Type");
            if (!"application/vnd.android.package-archive".equals(type)) {
                AppLog.e("download url 非 apk文件");
                return null;
            }

            AppLog.d("start downloading ... ");
            // make file
            final String fileName = System.currentTimeMillis() + ".apk";
            File tmpFile = new File(DownloadPath);
            if (!tmpFile.exists()) {
                tmpFile.mkdir();
            }
            final File file = new File(DownloadPath + "/" + fileName);
            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);

            // save
            byte[] buf = new byte[1024 * 10];
            int numRead = -1;
            while ((numRead = is.read(buf)) > 0) {
                //AppLog.d("read " + numRead + " bytes");
                fos.write(buf, 0, numRead);
            }
            conn.disconnect();
            fos.close();
            is.close();
            AppLog.d("download complete:url=" + url);
            return file;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}